<template>
    <view class="container">
        <view class="header">
            <view class="back-button" @tap="goBack">
                <text class="back-icon">←</text>
            </view>
            <view class="title">{{ title }}</view>
        </view>
        
        <scroll-view 
            scroll-y="true" 
            class="content-area" 
            :enhanced="true"
            :bounces="true"
            :show-scrollbar="true">
            <!-- 错误显示 -->
            <error-display 
                :show="showError" 
                :title="errorTitle" 
                :message="errorMessage" 
                @retry="retryLoading"
            />
            
            <!-- 加载中显示 -->
            <view class="loading-container" v-if="isLoading">
                <view class="loading-spinner"></view>
                <text class="loading-text">加载中...</text>
            </view>
            
            <!-- 内容显示 -->
            <rich-text :nodes="renderedContent" v-if="!showError && !isLoading"></rich-text>
            
            <!-- 底部空间 -->
            <view class="bottom-space"></view>
        </scroll-view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { marked } from 'marked';
import { onLoad } from '@dcloudio/uni-app';
import content from '@/common/api/content.js';
const contentAPI = content.content;
const legacyAPI = content.page;
import ErrorDisplay from '@/components/ErrorDisplay.vue';

// 安全解码函数：避免 URI malformed 错误
const safeDecodeURIComponent = (str) => {
    try {
        // 只有包含 % 符号时才尝试解码
        if (str && str.includes('%')) {
            return decodeURIComponent(str);
        }
        return str;
    } catch (error) {
        // console.warn('URI解码失败，使用原始字符串:', error.message);
        return str;
    }
};

const title = ref('');
const markdownContent = ref('');
const renderedContent = ref('');
const category = ref('');
const filename = ref('');
const endpoint = ref('');
const isLoading = ref(true);
const showError = ref(false);
const errorTitle = ref('加载失败');
const errorMessage = ref('无法连接到服务器，请检查网络连接');
const currentOptions = ref(null);

// 配置marked添加类名
marked.use({
    renderer: {
        heading(text, level) {
            return `<h${level} class="md-heading md-h${level}">${text}</h${level}>`;
        },
        paragraph(text) {
            return `<p class="md-paragraph">${text}</p>`;
        },
        list(body, ordered) {
            const tag = ordered ? 'ol' : 'ul';
            const className = ordered ? 'md-ordered-list' : 'md-unordered-list';
            return `<${tag} class="${className}">${body}</${tag}>`;
        },
        listitem(text) {
            return `<li class="md-list-item">${text}</li>`;
        },
        link(href, title, text) {
            return `<a class="md-link" href="${href}"${title ? ` title="${title}"` : ''}>${text}</a>`;
        },
        image(href, title, text) {
            return `<img class="md-image" src="${href}" alt="${text}"${title ? ` title="${title}"` : ''}>`;
        },
        blockquote(quote) {
            return `<blockquote class="md-blockquote">${quote}</blockquote>`;
        },
        code(code, language) {
            return `<pre class="md-pre"><code class="md-code ${language ? `language-${language}` : ''}">${code}</code></pre>`;
        },
        table(header, body) {
            return `<table class="md-table"><thead>${header}</thead><tbody>${body}</tbody></table>`;
        },
        tablerow(content) {
            return `<tr class="md-table-row">${content}</tr>`;
        },
        tablecell(content, { header }) {
            const tag = header ? 'th' : 'td';
            const className = header ? 'md-table-header' : 'md-table-cell';
            return `<${tag} class="${className}">${content}</${tag}>`;
        }
    }
});

// 监听页面参数
onLoad((options) => {
    currentOptions.value = options;
    
    if (options.title) {
        title.value = safeDecodeURIComponent(options.title);
    }
    
    loadContent(options);
});

// 加载内容
const loadContent = (options) => {
    isLoading.value = true;
    showError.value = false;
    
    // 直接传递内容的情况
    if (options.content) {
        try {
            const decodedContent = safeDecodeURIComponent(options.content);
            markdownContent.value = decodedContent;
            renderedContent.value = marked(decodedContent);
            isLoading.value = false;
        } catch (error) {
            console.error('内容处理失败:', error);
            showError.value = true;
            errorTitle.value = '内容解析失败';
            errorMessage.value = '无法解析传递的内容';
            isLoading.value = false;
        }
    }
    // 通过API端点加载内容的情况
    else if (options.endpoint) {
        try {
            const decodedEndpoint = safeDecodeURIComponent(options.endpoint);
            endpoint.value = decodedEndpoint;
            // console.log('解码后的端点:', decodedEndpoint);
            loadContentFromEndpoint(decodedEndpoint);
        } catch (error) {
            console.error('端点处理失败:', error);
            showError.value = true;
            errorTitle.value = '端点解析失败';
            errorMessage.value = '无法解析API端点';
            isLoading.value = false;
        }
    }
    // 通过分类和文件名加载内容的情况
    else if (options.category && options.filename) {
        category.value = options.category;
        filename.value = options.filename;
        title.value = options.filename;
        loadContentFromApi(options.category, options.filename);
    } else {
        isLoading.value = false;
        showError.value = true;
        errorTitle.value = '参数错误';
        errorMessage.value = '缺少必要的参数，无法加载内容';
    }
};

// 重试加载
const retryLoading = () => {
    if (currentOptions.value) {
        loadContent(currentOptions.value);
    }
};

// 从API端点加载内容
const loadContentFromEndpoint = async (endpoint) => {
    try {
        // console.log('从端点加载内容:', endpoint);
        
        // 使用新的内容API
        const response = await contentAPI.getContent(endpoint);
        
        if (response.data && response.data.content) {
            markdownContent.value = response.data.content;
            renderedContent.value = marked(response.data.content);
        } else {
            throw new Error('API返回的数据格式不正确');
        }
        
        isLoading.value = false;
    } catch (error) {
        console.error('从端点加载内容失败:', error);
        isLoading.value = false;
        showError.value = true;
        errorTitle.value = '加载失败';
        errorMessage.value = error.message || '无法从API端点加载内容';
    }
};

// 从API加载内容（兼容旧版）
const loadContentFromApi = async (category, filename) => {
    try {
        // console.log('从API加载内容:', category, filename);
        
        // 尝试使用新的内容API
        try {
            const path = `${category}/${filename}`;
            const response = await contentAPI.getContent(path);
            
            if (response.data && response.data.content) {
                markdownContent.value = response.data.content;
                renderedContent.value = marked(response.data.content);
                isLoading.value = false;
                return;
            }
        } catch (newApiError) {
            // console.log('新API失败，尝试旧版API:', newApiError);
        }
        
        // 如果新API失败，尝试旧版API
        const response = await legacyAPI.getCategoryContent(category, filename);
        
        if (response.data) {
            markdownContent.value = response.data;
            renderedContent.value = marked(response.data);
        } else {
            throw new Error('API返回的数据格式不正确');
        }
        
        isLoading.value = false;
    } catch (error) {
        console.error('从API加载内容失败:', error);
        isLoading.value = false;
        showError.value = true;
        errorTitle.value = '加载失败';
        errorMessage.value = error.message || '无法从API加载内容';
    }
};

// 返回上一页
const goBack = () => {
    uni.navigateBack();
};
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #fff;
}

/* 头部样式 */
.header {
    display: flex;
    align-items: center;
    padding: calc(20rpx + 44px) 30rpx 20rpx;
    background-color: #1e3c72;
    color: #fff;
    position: relative;
}

.back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    margin-right: 20rpx;
}

.back-icon {
    font-size: 32rpx;
    font-weight: bold;
}

.title {
    flex: 1;
    font-size: 36rpx;
    font-weight: 600;
    text-align: center;
    margin-right: 80rpx;
}

/* 内容区域样式 */
.content-area {
    flex: 1;
    padding: 30rpx;
    overflow-y: auto;
}

/* 加载中样式 */
.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #1e3c72;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
}

/* Markdown样式 */
.md-heading {
    margin: 30rpx 0 20rpx 0;
    font-weight: 600;
    color: #333;
    line-height: 1.4;
}

.md-h1 {
    font-size: 48rpx;
    border-bottom: 4rpx solid #1e3c72;
    padding-bottom: 20rpx;
}

.md-h2 {
    font-size: 40rpx;
    border-bottom: 2rpx solid #e0e0e0;
    padding-bottom: 15rpx;
}

.md-h3 {
    font-size: 36rpx;
}

.md-h4 {
    font-size: 32rpx;
}

.md-h5 {
    font-size: 28rpx;
}

.md-h6 {
    font-size: 24rpx;
}

.md-paragraph {
    margin: 20rpx 0;
    line-height: 1.8;
    color: #333;
    font-size: 28rpx;
}

.md-unordered-list,
.md-ordered-list {
    margin: 20rpx 0;
    padding-left: 40rpx;
}

.md-list-item {
    margin: 10rpx 0;
    line-height: 1.6;
    color: #333;
    font-size: 28rpx;
}

.md-link {
    color: #1e3c72;
    text-decoration: underline;
}

.md-image {
    max-width: 100%;
    height: auto;
    margin: 20rpx 0;
    border-radius: 8rpx;
}

.md-blockquote {
    margin: 20rpx 0;
    padding: 20rpx 30rpx;
    background-color: #f8f9fa;
    border-left: 8rpx solid #1e3c72;
    border-radius: 8rpx;
    font-style: italic;
    color: #666;
}

.md-pre {
    margin: 20rpx 0;
    padding: 20rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    overflow-x: auto;
}

.md-code {
    font-family: 'Courier New', monospace;
    font-size: 24rpx;
    color: #333;
}

.md-table {
    width: 100%;
    margin: 20rpx 0;
    border-collapse: collapse;
    border: 2rpx solid #e0e0e0;
}

.md-table-header,
.md-table-cell {
    padding: 15rpx;
    border: 1rpx solid #e0e0e0;
    text-align: left;
    font-size: 26rpx;
}

.md-table-header {
    background-color: #f8f9fa;
    font-weight: 600;
    color: #333;
}

.md-table-cell {
    color: #333;
}

/* 底部空间 */
.bottom-space {
    height: 100rpx;
}

/* ===== Markdown 样式 (手动同步) ===== */
/* 同步时间: 2025/7/24 23:45:00 */
/* 来源: admin/src/assets/unified-markdown.css */

/* ===== 基础样式 ===== */
.md-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif;
  line-height: 1.6;
  color: #333;
  max-width: 100%;
  word-wrap: break-word;
}

/* ===== 标题样式 ===== */
.md-heading {
  margin: 48rpx 0 26rpx 0;
  font-weight: 600;
  line-height: 1.25;
  color: #1a1a1a;
}

.md-h1 {
  font-size: 64rpx;
  border-bottom: 6rpx solid #4a90e2;
  padding-bottom: 16rpx;
  margin-top: 0;
}

.md-h2 {
  font-size: 48rpx;
  border-bottom: 4rpx solid #6bb6ff;
  padding-bottom: 10rpx;
}

.md-h3 {
  font-size: 40rpx;
  color: #2c3e50;
}

.md-h4 {
  font-size: 35rpx;
  color: #34495e;
}

.md-h5 {
  font-size: 32rpx;
  color: #5d6d7e;
}

.md-h6 {
  font-size: 29rpx;
  color: #6c757d;
}

/* ===== 段落样式 ===== */
.md-paragraph {
  margin: 32rpx 0;
  line-height: 1.7;
  color: #333;
}

/* ===== 列表样式 ===== */
.md-unordered-list,
.md-ordered-list {
  margin: 32rpx 0;
  padding-left: 64rpx;
}

.md-list-item {
  margin: 16rpx 0;
  line-height: 1.6;
}

/* ===== 链接样式 ===== */
.md-link {
  color: #4a90e2;
  text-decoration: none;
}

/* ===== 图片样式 ===== */
.md-image {
  max-width: 100%;
  height: auto;
  margin: 32rpx 0;
  border-radius: 16rpx;
}

/* ===== 引用块样式 ===== */
.md-blockquote {
  margin: 48rpx 0;
  padding: 32rpx 48rpx;
  background-color: #f8f9fa;
  border-left: 8rpx solid #4a90e2;
  border-radius: 0 16rpx 16rpx 0;
  font-style: italic;
  color: #5a6c7d;
}

/* ===== 内联代码样式 ===== */
.md-inline-code {
  background-color: #f1f3f4;
  color: #d73a49;
  padding: 6rpx 13rpx;
  border-radius: 8rpx;
  font-family: Consolas, monospace;
  font-size: 29rpx;
  font-weight: 500;
}

/* ===== 代码块样式 ===== */
.md-code-block {
  margin: 48rpx 0;
  position: relative;
  border-radius: 24rpx;
  overflow: hidden;
  background: #1e1e1e;
}

.md-language-label {
  position: absolute;
  top: 24rpx;
  right: 32rpx;
  background: rgba(255, 255, 255, 0.1);
  color: #888;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-family: monospace;
  text-transform: uppercase;
  letter-spacing: 1rpx;
  z-index: 2;
}

.md-pre {
  margin: 0;
  padding: 80rpx 48rpx 48rpx 48rpx;
  background: #1e1e1e;
  overflow-x: auto;
  position: relative;
}

/* macOS 风格窗口按钮 */
.md-pre::before {
  content: "";
  display: block;
  position: absolute;
  top: 32rpx;
  left: 32rpx;
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #ff5f56;
  box-shadow: 40rpx 0 0 #ffbd2e, 80rpx 0 0 #27c93f;
  z-index: 1;
}

.md-code {
  font-family: Consolas, monospace;
  font-size: 28rpx;
  line-height: 1.5;
  color: #d4d4d4;
  background: none;
  display: block;
  white-space: pre;
  word-spacing: normal;
  word-break: normal;
  tab-size: 4;
}

/* ===== Prism.js 语法高亮颜色 - VS Code Dark+ 主题 ===== */
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
  color: #6a9955;
  font-style: italic;
}

.token.punctuation {
  color: #cccccc;
}

.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
  color: #b5cea8;
}

.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
  color: #ce9178;
}

.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
  color: #d4d4d4;
}

.token.atrule,
.token.attr-value,
.token.keyword {
  color: #569cd6;
}

.token.function,
.token.class-name {
  color: #dcdcaa;
}

.token.regex,
.token.important,
.token.variable {
  color: #9cdcfe;
}

.token.important,
.token.bold {
  font-weight: bold;
}

.token.italic {
  font-style: italic;
}

/* ===== 表格样式 ===== */
.md-table-wrapper {
  margin: 48rpx 0;
  overflow-x: auto;
  border-radius: 16rpx;
}

.md-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  font-size: 28rpx;
}

.md-table-header {
  background: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
  padding: 24rpx 32rpx;
  text-align: left;
  border-bottom: 4rpx solid #e9ecef;
}

.md-table-cell {
  padding: 24rpx 32rpx;
  border-bottom: 2rpx solid #e9ecef;
  color: #495057;
}

.md-table-row:nth-child(even) {
  background-color: #f8f9fa;
}

/* ===== 分割线样式 ===== */
.md-divider {
  margin: 64rpx 0;
  border: none;
  height: 4rpx;
  background: linear-gradient(to right, transparent, #4a90e2, transparent);
}

/* ===== 文本样式 ===== */
.md-strong {
  font-weight: 600;
  color: #2c3e50;
}

.md-em {
  font-style: italic;
  color: #5a6c7d;
}

.md-del {
  text-decoration: line-through;
  color: #6c757d;
  opacity: 0.7;
}
</style>